
/**
 * @description 背景色 backColor
 * @author zengqiongying
*/
import Colorpicker from './colorPicker'
import ColorList from './colorList'
import E from 'wangeditor'
const { $, DropListMenu } = E

// 菜单 class DropListMenu 菜单继承 DropListMenu class
class BackFont extends DropListMenu {
  constructor(editor) {
    // data-title属性表示当鼠标悬停在该按钮上时提示该按钮的功能简述
    const $elem = E.$(
      `<div class="w-e-menu qup-we-color-picker back-color" data-title="背景颜色">
         <span class='we-icon-back-color'>a</span><span class='we-icon-back-color'>b</span>
         <div class="underline"></div>
       </div>`
    )
    // editor.config.colors = colors
    const colorDplList = new ColorList().getItemList()
    const colorListConf = {
      width: 216,
      title: '背景颜色',
      // droplist 内容以 block 形式展示
      type: 'inline-block',
      list: colorDplList,
      clickHandler: (value) => {
        // this 是指向当前的 BackFont 对象
        if (value !== 'more') {
          this.command(value)
        } else {
          const _this = this
          const curDrop = $elem.elems[0].getElementsByClassName('w-e-droplist')[0]
          setTimeout(() => {
            curDrop.style.display = 'block' // todo:点击li后默认关闭颜色面板，延时处理保持颜色面板打开
          }, 20)
          const colorMoreEl = $elem.elems[0].getElementsByClassName('lake-more-color')[0]
          const colorPickerObj = Colorpicker.create({
            el: colorMoreEl,
            color: '#000000',
            change: function(elem, hex) {
              _this.command(hex)
            },
            open: () => {
              curDrop.style.display = 'block'
            },
            close: () => {
              curDrop.style.display = 'none'
            }
          })
        }
      }
    }
    super($elem, editor, colorListConf)
  }
  command(value) {
    const editor = this.editor
    const isEmptySelection = editor.selection.isSelectionEmpty()
    const $selectionElem = editor.selection.getSelectionContainerElem() ? editor.selection.getSelectionContainerElem().elems[0] : null

    if ($selectionElem == null) return

    const isSpan = $selectionElem ? $selectionElem.nodeName.toLowerCase() !== 'p' : false
    const bgColor = $selectionElem ? $selectionElem.style.backgroundColor : ''
    const isSameColor = hexToRgb(value) === bgColor

    if (isEmptySelection) {
      if (isSpan && !isSameColor) {
        const $elems = editor.selection.getSelectionRangeTopNodes()
        editor.selection.createRangeByElem($elems[0])
        editor.selection.moveCursor($elems[0].elems[0])
      }
      // 插入空白选区
      editor.selection.createEmptyRange()
    }

    editor.cmd.do('backColor', value)

    if (isEmptySelection) {
      // 需要将选区范围折叠起来
      editor.selection.collapseRange()
      editor.selection.restoreSelection()
    }
  }
  // 菜单是否被激活（如果不需要，这个函数可以空着）
  // 1. 激活是什么？光标放在一段加粗、下划线的文本时，菜单栏里的 B 和 U 被激活，如下图
  // 2. 什么时候执行这个函数？每次编辑器区域的选区变化（如鼠标操作、键盘操作等），都会触发各个菜单的 tryChangeActive 函数，重新计算菜单的激活状态
  tryChangeActive() {
    // 激活菜单
    // 1. 菜单 DOM 节点会增加一个 .w-e-active 的 css class
    // 2. this.this.isActive === true

    // // 取消激活菜单
    // // 1. 菜单 DOM 节点会删掉 .w-e-active
    // // 2. this.this.isActive === false
    // this.unActive()
    const editor = this.editor
    // 获取到当前背景颜色值
    const colorValue = editor.cmd.queryCommandValue('backColor')
    const colorTool = editor.$toolbarElem.elems[0].getElementsByClassName('back-color')[0]
    const underline = colorTool.getElementsByClassName('underline')[0]
    underline.style.backgroundColor = colorValue

    /*
    const rgbArr = colorValue.match(/[^\(\)]+(?=\))/g)[0].split(',') // 取rgb值
    const hexValue = rgbToHex(rgbArr) // rgb值转换为hex值
    // const toolChildren = editor.$toolbarElem.elems[0].toolChildren
     const colorItems = colorTool.getElementsByClassName('color-picker')
    if (colorItems && colorItems.length) {
      for (const el of colorItems) {
        console.log(el)
        if (el.style.backgroundColor === colorValue) {
          el.className = 'color-picker active'
        } else {
          el.className = 'color-picker'
        }
      }
    } */

    /* if (hexValue) {
      this.active()
    } else {
      this.unActive()
    } */
  }
}

function hexToRgb(hex) {
  const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)

  if (result == null) return null

  const colors = result.map(i => parseInt(i, 16))
  const r = colors[1]
  const g = colors[2]
  const b = colors[3]

  return `rgb(${r}, ${g}, ${b})`
}

function rgbToHex(rgb) {
  const hex = rgb.map(v => {
    return parseInt(v).toString(16)
  })
  hex.map(function(str, i) {
    if (str.length === 1) {
      hex[i] = '0' + str
    }
  })

  return `#${hex.join('')}`
}

export default BackFont
